<template>
  <div class="app-container">
    <el-dialog :model-value="itemsVisible" title="选择事前用款申请单" :append-to-body="true" width="80%" height="1000px" @close="closeBtn">
      <div class="filter-container">
        <el-form :inline="true" :model="listQuery" class="demo-form-inline">
          <el-form-item label="指标单">
            <el-input v-model="props.expenditureKpiCode" placeholder="指标单" @keyup.enter="handleFilter" style="width: 370px;" disabled />
          </el-form-item>
          <el-form-item prop="applicationCode" label="申请单号">
            <el-input v-model="listQuery.applicationCode" placeholder="申请单号" @keyup.enter="handleFilter" />
          </el-form-item>
          <el-form-item label="申请日期">
            <el-date-picker v-model="listQuery.applicationDateRange"
                            value-format="YYYY-MM-DD"
                            style="width: 300px"
                            type="daterange"
                            range-separator="-"
                            start-placeholder="申请日期开始"
                            end-placeholder="申请日期结束" />
          </el-form-item>
          <el-form-item prop="applicationType" label="用款申请单类型">
            <el-select v-model="listQuery.applicationType" class="m-2" placeholder="请选择">
              <el-option key="" label="全部" value="" />
              <el-option v-for="item in getDictList('ExpenditureApplicationType')" :key="item.key" :label="`${item.key} - ${item.value}`" :value="item.key" />
            </el-select>
          </el-form-item>
          <!--
          <el-form-item prop="items" label="请款事项">
            <el-input v-model="listQuery.items" placeholder="请款事项" @keyup.enter="handleFilter" />
          </el-form-item>
          <el-form-item prop="reason" label="支出事由">
            <el-input v-model="listQuery.reason" placeholder="支出事由" @keyup.enter="handleFilter" />
          </el-form-item>
          -->
          <el-form-item prop="applicationOrganizationId" label="申请人部门">
            <Organization v-model="listQuery.applicationOrganizationId" keyName="id" keyShow="organizationName" placeholder="申请人部门" title="部门查询" />
          </el-form-item>
          <el-form-item prop="applicationUserId" label="申请人用户">
            <User v-model="listQuery.applicationUserId" keyName="id" keyShow="name" placeholder="申请人用户" title="用户查询" />
          </el-form-item>
          <el-form-item prop="state" label="状态">
            <el-radio-group v-model="listQuery.state" disabled>
              <el-radio-button label="" key="">全部</el-radio-button>
              <el-radio-button v-for="(item,index) in getEnumList('ExpenditureApplicationState')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <el-button v-waves type="success" icon="Search" @click="handleFilter">
              查询
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="app-container">
        <el-table v-loading="listLoading"
                  :data="indexsList"
                  border
                  fit
                  highlight-current-row
                  tooltip-effect="dark"
                  style="width: 100%; margin-bottom: 20px;">
          <el-table-column align="center" type="index" label="序号" width="60px" />
          <el-table-column align="center" label="申请单号" prop="applicationCode" min-width="120px" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" label="申请日期" prop="applicationDate" min-width="120px" show-overflow-tooltip>
            <template v-slot="{row}">{{ row.applicationDate?.substring(0, 10) }}</template>
          </el-table-column>
          <el-table-column align="center" label="用款申请单类型" prop="applicationType" min-width="170px" show-overflow-tooltip>
            <template v-slot="{row}">
              <DictTag :dict-list="getDictList('ExpenditureApplicationType')" :dict-key="row.applicationType"/>
            </template>
          </el-table-column>
          <el-table-column align="center" label="申请金额" prop="amount" min-width="120px" show-overflow-tooltip>
            <template v-slot="{row}"><MoneyTag :money="row.amount" /></template>
          </el-table-column>
          <el-table-column align="center" label="请款事项" prop="items" min-width="120px" show-overflow-tooltip>
            <template v-slot="{row}">{{ row.items }}</template>
          </el-table-column>
          <el-table-column align="center" label="支出事由" prop="reason" min-width="120px" show-overflow-tooltip>
            <template v-slot="{row}">{{ row.reason }}</template>
          </el-table-column>
          <el-table-column align="center" label="申请人部门" prop="applicationOrganizationId" min-width="120px" show-overflow-tooltip>
            <template v-slot="{row}">{{ showIdLabel(organizationList, row.applicationOrganizationId, 'organizationName') }}</template>
          </el-table-column>
          <el-table-column align="center" label="申请人用户" prop="applicationUserId" min-width="120px" show-overflow-tooltip>
            <template v-slot="{row}">{{ showIdLabel(userList, row.applicationUserId, 'name') }}</template>
          </el-table-column>
          <el-table-column align="center" label="状态" prop="state" min-width="120px" show-overflow-tooltip>
            <template v-slot="{row}">
              <EnumTag :enum-list="getEnumList('ExpenditureApplicationState')" :enum-key="row.state" />
            </template>
          </el-table-column>
          <el-table-column align="center" label="备注" prop="remark" min-width="80px" show-overflow-tooltip>
            <template v-slot="{row}">{{ row.remark }}</template>
          </el-table-column>
          <el-table-column align="center" label="创建时间" width="180px" prop="createTime" sortable show-overflow-tooltip>
            <template v-slot="{row}"><DateTag :timestamp="row.createTime" /></template>
          </el-table-column>
          <el-table-column align="center" label="最后修改时间" width="180px" prop="updateTime" sortable show-overflow-tooltip>
            <template v-slot="{row}"><DateTag :timestamp="row.updateTime" /></template>
          </el-table-column>
          <el-table-column label="选择申请单" width="150" align="center" fixed="right">
            <template v-slot="{row}">
              <el-radio :label="row.id" v-model="tableRadio" border @click="handleCurrentChange($event, row)">选择</el-radio>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-model:total="total" v-model:page="listQuery.pageNum" v-model:limit="listQuery.pageSize" @pagination="getList" class="pagination-model" />
        <div style="text-align:right;margin: 1.875rem 0;">
          <el-button type="danger" @click="closeBtn">关闭</el-button>
          <el-button type="primary" @click="onSureBtn">确定</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script setup>
import {ref, watch} from 'vue'
import {doGet} from "@/config/http";
import {
  svc,
  getDictList,
  getEnumList,
  alertErrorMsg,
  getListPageSize, showIdLabel
} from "@/config/common";
import useUserStore from "@/store/modules/user";
import {getUserId} from "@/config/cookie";
import User from "@/views/components/base/selectUser.vue";
import Organization from "@/views/components/base/selectOrganization.vue";
import initListStore from '@/store/modules/initList'

const props = defineProps({
  itemsVisible: {
    required: true,
    type: Boolean,
  },
  state: {
    required: false,
    type: String,
  },
  expenditureKpiId: {
    required: true,
    type: String,
  },
  expenditureKpiCode: {
    required: true,
    type: String,
  },
  expenditureApplicationId: {
    required: false,
    type: String,
  },
})

let indexsList = ref([])
let tableRadio = ref('')
let listLoading = ref(true)
let total = ref(0)

let listQuery = ref({
  expenditureKpiId: null, // 指标单表ID
  applicationCode: null, // 申请单号
  applicationDate: null, // 申请日期
  applicationType: null, // 用款申请单类型
  amount: null, // 申请金额
  items: null, // 请款事项
  reason: null, // 支出事由
  applicationOrganizationId: useUserStore().organization.organizationType !== '1' ? useUserStore().organization.id : '',
  applicationUserId: useUserStore().organization.organizationType !== '1' ? getUserId() : '',
  state: '2', // 状态
  remark: null, // 备注
  id: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  deleted: null,
  version: null,
  applicationDateRange: [],
})
let radioRow = null

let governmentList = initListStore().governmentList
let organizationList = initListStore().organizationList
let userList = initListStore().userList

const emit = defineEmits(['close', 'expenditureApplicationSelect'])

watch(() => [props.itemsVisible, props.expenditureKpiId, props.expenditureApplicationId], async vals => {
  if (vals[0] === true) {
    listQuery.value.expenditureKpiId = vals[1]
    await getList()
    // await initList()
    if (vals[2]) {
      tableRadio.value = vals[2]
    }
  }
})

// async function initList() {
//   let p1 = doGet(svc, '/government/page', {pageSize: getListPageSize()}, false)
//   let p2 = doGet(svc, '/organization/page', {pageSize: getListPageSize()}, false)
//   let p3 = doGet(svc, '/user/page', {pageSize: getListPageSize()}, false)
//   let resArray = await Promise.all([p1, p2, p3])
//   governmentList.value = resArray[0]['records']
//   organizationList.value = resArray[1]['records']
//   userList.value = resArray[2]['records']
// }

// 获取数据
async function getList() {
  listLoading.value = true
  listQuery.value.applicationDateStart = ''
  listQuery.value.applicationDateEnd = ''
  if (listQuery.value.applicationDateRange) {
    listQuery.value.applicationDateStart = listQuery.value.applicationDateRange[0]
    listQuery.value.applicationDateEnd = listQuery.value.applicationDateRange[1]
  }
  let res = await doGet(svc, '/expenditure-application/page', listQuery.value)
  listLoading.value = false
  total.value = parseInt(res['total'])
  indexsList.value = res['records']
}

// 查询
async function handleFilter() {
  listQuery.value['pageNum'] = 1
  await getList()
}

// 关闭弹层
function closeBtn(val) {
  console.debug(val)
  emit('close')
}

// 选择
function handleCurrentChange(val, row) {
  radioRow = row
}

// 点确定
function onSureBtn() {
  if (!radioRow) {
    alertErrorMsg('请选择用款申请单')
    return
  }
  emit('expenditureApplicationSelect', radioRow)
  emit('close')
}
</script>
